package com.tianji.aigc.advisor;

import cn.hutool.core.convert.Convert;
import com.tianji.aigc.enums.AgentTypeEnum;
import com.tianji.aigc.memory.MyChatMemoryRepository;
import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.advisor.api.AdvisorChain;
import org.springframework.ai.chat.client.advisor.api.BaseAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatResponse;

import java.lang.management.MemoryType;

public class RecordOptimizationAdvisor implements BaseAdvisor {

    private final MyChatMemoryRepository myChatMemoryRepository;

    public RecordOptimizationAdvisor(MyChatMemoryRepository myChatMemoryRepository) {
        this.myChatMemoryRepository = myChatMemoryRepository;
    }
    @Override
    public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChain advisorChain) {
        return chatClientRequest;
    }


    @Override
    public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) {
        ChatResponse response = chatClientResponse.chatResponse();
        String output = response.getResult().getOutput().getText();
        AgentTypeEnum agentTypeEnum = AgentTypeEnum.agentNameOf(output);
        if (agentTypeEnum != null){
            String key = ChatMemory.CONVERSATION_ID;
            String conversationId  = Convert.toStr(chatClientResponse.context().get(key));
            myChatMemoryRepository.optimization(conversationId );
        }
        return chatClientResponse;
    }

    /**
     * 优先级
     * @return
     */
    @Override
    public int getOrder() {
        return RecordOptimizationAdvisor.DEFAULT_CHAT_MEMORY_PRECEDENCE_ORDER-100;
    }
}
